var optionsDate, optionsTime, optionsNumeric, moneyNumeric, optionsShiftAllw, optionsMealAllw, optionsBreakHours,
    ERROR_STATUS_COLOR,
    NORMAL_STATUS_COLOR;

ERROR_STATUS_COLOR = "#ff0000";
NORMAL_STATUS_COLOR = "#ffffff";

optionsDate = {
    format: "dd/MM/yyyy",
    parseFormats: [
    "dd/MMMM/yyyy",
    "dd-MMMMyyyy",
    "dd/MM/yyyy",
    "dd-MM-yyyy",
    "ddMMyyyy",
    "ddMMyy",
    "ddMM"
    ],
    max: new Date((new Date()).getFullYear(), (new Date()).getMonth(), (new Date()).getDate()),
    change: function (a, b, c) {
        if ((this.value() === null) && ($.trim($("#claimDate").val()).length > 0)) {
            this.value("");
        }
    }
}; // optionsDate = {

optionsTime = {
    interval: 15,
    format: "HHmm",
    parseFormats: [
    "HHmm",
    "Hmm",
    "HH",
    "H"
    ], //format also will be added to parseFormats
    change: function (e) {
    }
}; // optionsTime = {

optionsNumeric = {
    spinners: false,
    format: "0.##",
    min: 0,
    decimals: 2,
    change: function () {
        var value = this.value();
    }
}; // optionsNumeric = {

optionsBreakHours = {
    dataTextField: "text",
    dataValueField: "value",
    dataSource: [
        { text: "", value: "" },
        { text: "0.5", value: "0.5" },
        { text: "0.75", value: "0.75" },
        { text: "1", value: "1" },
        { text: "1.25", value: "1.25" },
        { text: "1.5", value: "1.5" },
        { text: "1.75", value: "1.75" },
        { text: "2", value: "2" }
    ],
    index: 0
};

optionsShiftAllw = {
    dataTextField: "text",
    dataValueField: "value",
    dataSource: [
        { text: "", value: "" },
        { text: "8", value: "8" }
    ],
    index: 0
};

optionsMealAllw = {
    dataTextField: "text",
    dataValueField: "value",
    dataSource: [
        { text: "", value: "" },
        { text: "4", value: "4" }
    ],
    index: 0
};

moneyNumeric = {
    spinners: false,
    format: "0.00",
    min: 0,
    decimals: 2,
    change: function () {
        var value = this.value();

    }
}; // moneyNumeric = {


function ConvertTimeToDate(strValue, addHours) {
    var hours, minutes, meridian;

    if (strValue.length != 4)
        return NaN;

    hours = strValue.substring(0, 2);
    minutes = strValue.substring(2, 4);

    if (parseInt(hours, 10) < 12)
        meridian = "AM"
    else
        meridian = "PM"

    if ((hours === "00") && (minutes === "00"))
    {
        //if (minutes !== "00") {
        //    return NaN;
        //}

        hours = hours + addHours;
    }

    return parseTime(hours + ":" + minutes + " " + meridian);
}

function parseTime(timeStr, dt) {
    if (!dt) {
        dt = new Date();
    }

    var time = timeStr.match(/(\d+)(?::(\d\d))?\s*(p?)/i);
    if (!time) {
        return NaN;
    }
    var hours = parseInt(time[1], 10);
    if (hours == 12 && !time[3]) {
        hours = 0;
    }
    else {
        hours += (hours < 12 && time[3]) ? 12 : 0;
    }

    dt.setHours(hours);
    dt.setMinutes(parseInt(time[2], 10) || 0);
    dt.setSeconds(0, 0);
    return dt;
}

function validateAddClaim() {
    var claimDate,
        claimStartWorkTime,
        claimEndWorkTime,
        claimStartOT,
        claimEndOT,
        claimHours_OT1_5,
        claimHours_OT2_0,
        claimHours_PH,
        claimHours_Less4H,
        claimHours_More4H,
        claimAllowance_Meal,
        claimAllowance_Shift,
        claimBreakHours,
        claimShiftType,
        claimRemark,
        startOT,
        endOT,
        claimableHours,
        claimedHours,
        stdPartingMessage = "<p>Please correct errors before attempting to add again.</p>",
        isFormValid = true;

    claimDate = $("#claimDate").data("kendoDatePicker").value();
    claimStartWorkTime = $("#claimStartWorkTime").data("kendoTimePicker").value();
    claimEndWorkTime = $("#claimEndWorkTime").data("kendoTimePicker").value();
    claimStartOT = $("#claimStartOT").data("kendoTimePicker").value();
    claimEndOT = $("#claimEndOT").data("kendoTimePicker").value();
    claimHours_PH = $("#claimHours_PH").prop("checked");
    claimHours_Less4H = $("#claimHours_Less4H").prop("checked");
    claimHours_More4H = $("#claimHours_More4H").prop("checked");
    claimHours_OT1_5 = $("#claimHours_OT1_5").data("kendoNumericTextBox").value();
    claimHours_OT2_0 = $("#claimHours_OT2_0").data("kendoNumericTextBox").value();
    //claimAllowance_Meal = $("#claimAllowance_Meal").data("kendoNumericTextBox").value();
    //claimAllowance_Shift = $("#claimAllowance_Shift").data("kendoNumericTextBox").value();
    claimAllowance_Meal = $("#claimAllowance_Meal").data("kendoComboBox").value();
    claimAllowance_Shift = $("#claimAllowance_Shift").data("kendoComboBox").value();
    claimBreakHours = $("#claimBreakHours").data("kendoComboBox").value();
    claimShiftType = $.trim($("#claimShiftType").val());
    claimRemark = $.trim($("#claimRemark").val());

    if ((isFormValid) && (claimDate == null)) {
        $('#validationModalLabel').html("Validation error");
        $('#validationModalBody').html("Claim date is a required field." + stdPartingMessage);
        $('#validationModal').modal('show');
        isFormValid = false;
    }

    if ((isFormValid) && ((claimRemark == null) || (claimRemark == ""))) {
        $('#validationModalLabel').html("Validation error");
        $('#validationModalBody').html("Description of Work Performed During Overtime Hours Worked is a required field." + stdPartingMessage);
        $('#validationModal').modal('show');
        isFormValid = false;
    }

    if ((isFormValid) && 
        (claimStartWorkTime != null)) {
        if (claimEndWorkTime == null) {
            $('#validationModalLabel').html("Validation error");
            $('#validationModalBody').html("You need to fill in official end work time." + stdPartingMessage);
            $('#validationModal').modal('show');
            isFormValid = false;
        }
    }

    if ((isFormValid) &&
        (claimEndWorkTime != null)) {
        if (claimStartWorkTime == null) {
            $('#validationModalLabel').html("Validation error");
            $('#validationModalBody').html("You need to fill in official start work time." + stdPartingMessage);
            $('#validationModal').modal('show');
            isFormValid = false;
        }
    }

    if ((isFormValid) &&
        (claimStartOT != null)) {
        if (claimEndOT == null) {
            $('#validationModalLabel').html("Validation error");
            $('#validationModalBody').html("You need to fill in overtime end time." + stdPartingMessage);
            $('#validationModal').modal('show');
            isFormValid = false;
        }
    }

    if ((isFormValid) &&
        (claimEndOT != null)) {
        if (claimStartOT == null) {
            $('#validationModalLabel').html("Validation error");
            $('#validationModalBody').html("You need to fill in overtime start time." + stdPartingMessage);
            $('#validationModal').modal('show');
            isFormValid = false;
        }
    }

    if ((isFormValid) &&
        ((claimHours_OT1_5 == null) &&
        (claimHours_OT2_0 == null) &&
        (claimHours_PH == false) &&
        (claimHours_Less4H == false) &&
        (claimHours_More4H == false) &&
        (claimAllowance_Meal == null) &&
        (claimAllowance_Shift == null))) {
        $('#validationModalLabel').html("Validation error");
        $('#validationModalBody').html("Please fill in required fields." + stdPartingMessage);
        $('#validationModal').modal('show');
        isFormValid = false;
    }

    if ((isFormValid) &&
        (claimAllowance_Shift != "") &&
        (claimShiftType == "")) {
        $('#validationModalLabel').html("Validation error");
        $('#validationModalBody').html("You must indicate shift type to apply for shift allowance." + stdPartingMessage);
        $('#validationModal').modal('show');
        isFormValid = false;
    }

    if ((isFormValid) &&
        ((claimAllowance_Meal != null) && (claimAllowance_Meal != "")) &&
        ((claimStartOT == null) || (claimEndOT == null))) {
        $('#validationModalLabel').html("Validation error");
        $('#validationModalBody').html("You must indicate overtime hours to claim for meal allowance." + stdPartingMessage);
        $('#validationModal').modal('show');
        isFormValid = false;
    }

    if ((isFormValid) &&
        ((claimStartOT != null) && (claimEndOT != null))) {

        startOT = ConvertTimeToDate($("#claimStartOT").val(),0);
        //if ($("#claimStartOT").val() === "0000")
        //    startOT = new Date(startOT.getFullYear(), startOT.getMonth(), startOT.getDate() - 1);
        endOT = ConvertTimeToDate($("#claimEndOT").val(),24);
        claimableHours = (((endOT - startOT) / 1000) / 60) / 60;

        if (isNaN(claimableHours)) {
            $('#validationModalLabel').html("Validation error");
            $('#validationModalBody').html("The overtime that you have specified is not valid." + stdPartingMessage);
            $('#validationModal').modal('show');
            isFormValid = false;
        }
    }

    if ((isFormValid) && (claimHours_Less4H && (claimableHours > 4))) {
        $('#validationModalLabel').html("Validation error");
        $('#validationModalBody').html("You have checked <4 hour rest day but your overtime is more than 4 hours." + stdPartingMessage);
        $('#validationModal').modal('show');
        isFormValid = false;
    }

    if ((isFormValid) &&
        ((claimStartOT != null) && (claimEndOT != null))) {

        claimedHours = 0;
        if (claimHours_OT1_5 != null)
            claimedHours += claimHours_OT1_5;
        if (claimHours_OT2_0 != null)
            claimedHours += claimHours_OT2_0;

        // truncate  claimedHours and claimableHours to 2 decimal places.
        claimableHours = Math.floor(claimableHours * 100) / 100;
        claimedHours = Math.floor(claimedHours * 100) / 100;

        // Add adjustment for break hours
        claimableHours = claimableHours - claimBreakHours;

        // check to make sure overtime does not overlap working hours
        if ((claimStartWorkTime != null) && (claimEndWorkTime != null)) {
            if ((claimStartWorkTime < claimEndOT) && (claimEndWorkTime > claimStartOT)) {
                $('#validationModalLabel').html("Validation error");
                $('#validationModalBody').html("Your overtime cannot overlap with your official working hours." + stdPartingMessage);
                $('#validationModal').modal('show');
                isFormValid = false;
            }
        }

        if (($("#claimHours_More4H").prop("checked") === true) || (($("#claimHours_PH").prop("checked") === true) && ($("#claimShiftType").val().trim().length === 0))) {
        //if ((claimHours_More4H) || (claimHours_PH)) {
            claimableHours = claimableHours - 8;
            if (claimableHours < 0)
                claimableHours = 0;
        }

        if (claimHours_Less4H) {
            // no need to check OT for rest day <4 
            if (claimedHours > 0) {
                $('#validationModalLabel').html("Validation error");
                $('#validationModalBody').html("You cannot claim overtime hours when you checked rest day <4 hours." + stdPartingMessage);
                $('#validationModal').modal('show');
                isFormValid = false;
            }
        } else {
            // Check OT Rate
            if (claimableHours != claimedHours) {
                $('#validationModalLabel').html("Validation error");
                $('#validationModalBody').html("You claimed " + claimedHours + " of " + claimableHours + " claimable hours." + stdPartingMessage);
                $('#validationModal').modal('show');
                isFormValid = false;
            }
        }
    }

    return isFormValid;
}

function calculateTotalClaimableHours() {
    var $this = $(this),
                startOT, endOT, clockedHours, breakHours, claimableHours;

    $("#claimStartOT, #claimEndOT").css("background-color", NORMAL_STATUS_COLOR);

    startOT = ConvertTimeToDate($("#claimStartOT").val(),0);
    //if ($("#claimStartOT").val() === "0000")
    //    startOT = new Date(startOT.getFullYear(), startOT.getMonth(), startOT.getDate() - 1);
    endOT = ConvertTimeToDate($("#claimEndOT").val(),24);

    if (!isNaN(startOT) || !isNaN(endOT)) {
        if (isNaN(startOT)) {
            $("#claimStartOT").css("background-color", ERROR_STATUS_COLOR);
            $("#totalClockedHours").text("");
            return;
        } else {
            $("#claimStartOT").css("background-color", NORMAL_STATUS_COLOR);
        }

        if (isNaN(endOT)) {
            $("#claimEndOT").css("background-color", ERROR_STATUS_COLOR);
            $("#totalClockedHours").text("");
            return;
        } else {
            $("#claimEndOT").css("background-color", NORMAL_STATUS_COLOR);
        }

        //if (!isNaN(startOT) && isNaN(endOT)) {
        //    $("#claimEndOT").css("background-color", ERROR_STATUS_COLOR);
        //} else {
        //    $("#claimEndOT").css("background-color", NORMAL_STATUS_COLOR);
        //}
    }

    clockedHours = (((endOT - startOT) / 1000) / 60) / 60;
    clockedHours = Math.floor(clockedHours * 100) / 100;

    // Adjustment for break hours
    breakHours = parseFloat($("#claimBreakHours").val());
    if (isNaN(breakHours))
        breakHours = 0;
    claimableHours = clockedHours - breakHours;

    if (clockedHours < 0) {
        $("#claimStartOT, #claimEndOT").css("background-color", ERROR_STATUS_COLOR);
    }

    if (claimableHours >= 3) {
        $("#claimAllowance_Meal").data("kendoComboBox").value("4.00");
    } else {
        $("#claimAllowance_Meal").data("kendoComboBox").value("");
    }

    if (($("#claimHours_More4H").prop("checked") === true) || (($("#claimHours_PH").prop("checked") === true) && ($("#claimShiftType").val().trim().length === 0))) {
        //clockedHours = clockedHours - 8;
        claimableHours = claimableHours - 8;
        if (claimableHours < 0)
            claimableHours = 0;
    }
    

    $("#totalClockedHours").text(clockedHours);
    $("#claimTotalOTHours").val(clockedHours);
    $("#claimHours_OT1_5").data("kendoNumericTextBox").value(claimableHours);
}

(function ($) {
    "use strict";

    var ctlClaimDate,
        ctlClaimStartWorkTime,
        ctlClaimEndWorkTime,
        ctlClaimStartOT,
        ctlClaimEndOT,
        ctlClaimHours_OT1_5,
        ctlClaimHours_OT2_0,
        ctlClaimHours_PH,
        ctlClaimHours_Less4H,
        ctlClaimHours_More4H,
        ctlClaimAllowance_Shift,
        ctlClaimAllowance_Meal,
        ctlClaimBreakHours;

    $(document).ready(function () {

        ctlClaimDate = $("#claimDate").kendoDatePicker(optionsDate);
        ctlClaimStartWorkTime = $("#claimStartWorkTime").kendoTimePicker(optionsTime);
        ctlClaimEndWorkTime = $("#claimEndWorkTime").kendoTimePicker(optionsTime);
        ctlClaimStartOT = $("#claimStartOT").kendoTimePicker(optionsTime);
        ctlClaimEndOT = $("#claimEndOT").kendoTimePicker(optionsTime);
        ctlClaimHours_OT1_5 = $("#claimHours_OT1_5").kendoNumericTextBox(optionsNumeric);
        ctlClaimHours_OT2_0 = $("#claimHours_OT2_0").kendoNumericTextBox(optionsNumeric);
        //ctlClaimAllowance_Shift = $("#claimAllowance_Shift").kendoNumericTextBox(optionsNumeric);
        ctlClaimAllowance_Shift = $("#claimAllowance_Shift").kendoComboBox(optionsShiftAllw);
        ctlClaimBreakHours = $("#claimBreakHours").kendoComboBox(optionsBreakHours);
        //ctlClaimAllowance_Meal = $("#claimAllowance_Meal").kendoNumericTextBox(optionsNumeric);
        ctlClaimAllowance_Meal = $("#claimAllowance_Meal").kendoComboBox(optionsMealAllw);

        $("#claimDate").blur(function (e) {
            var $this = $(this),
                claimDate;

            claimDate = $("#claimDate").data("kendoDatePicker").value();

            if (claimDate === null) {
                $(this).css("background-color", ERROR_STATUS_COLOR);
                return;
            } else {
                $this.css("background-color", NORMAL_STATUS_COLOR);
            }
        });

        $("#claimStartWorkTime, #claimEndWorkTime").blur(function (e) {
            var startWorkTime, endWorkTime;
            startWorkTime = ConvertTimeToDate($("#claimStartWorkTime").val(), 0);
            endWorkTime = ConvertTimeToDate($("#claimEndWorkTime").val(), 24);

            $("#claimStartWorkTime, #claimEndWorkTime").css("background-color", NORMAL_STATUS_COLOR);
            if (!isNaN(startWorkTime) || !isNaN(endWorkTime)) {
                if (isNaN(startWorkTime)) {
                    $("#claimStartWorkTime").css("background-color", ERROR_STATUS_COLOR);
                    return;
                } else {
                    $("#claimStartWorkTime").css("background-color", NORMAL_STATUS_COLOR);
                }

                if (isNaN(endWorkTime)) {
                    $("#claimEndWorkTime").css("background-color", ERROR_STATUS_COLOR);
                    return;
                } else {
                    $("#claimEndWorkTime").css("background-color", NORMAL_STATUS_COLOR);
                }
            }
        });

        $("#claimStartOT, #claimEndOT").blur(function (e) {
            calculateTotalClaimableHours();
        });

        $("#claimHours_More4H").change(function (e) {
            calculateTotalClaimableHours();
        });

        $("#claimBreakHours").change(function (e) {
            calculateTotalClaimableHours();
        });

        $("#claimHours_PH").change(function (e) {
            calculateTotalClaimableHours();
        });
    });

}(jQuery));